//
//  XMLParser.m
//  RankingServiceTest
//
//  Created by Damia Ferrer on 16/10/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "XMLParser.h"
#import "CMNavBarAppDelegate.h"
#import "CarBean.h"

@implementation XMLParser

- (XMLParser *) initXMLParser {
    [super init];
    appDelegate = (CMNavBarAppDelegate *)[[UIApplication sharedApplication] delegate];
    return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
    attributes:(NSDictionary *)attributeDict {
    
    if([elementName isEqualToString:@"response"]) {
        //Initialize the array.
        appDelegate.cars = [[NSMutableArray alloc] init];
    }
    else if([elementName isEqualToString:@"car"]) {
        
        //Initialize the car.
        aCar = [[CarBean alloc] init];
    }
    
    NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    
    if(!currentElementValue)
        currentElementValue = [[NSMutableString alloc] initWithString:string];
    else
        [currentElementValue appendString:string];
    
    NSLog(@"Processing Value: %@", currentElementValue);
    
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    if([elementName isEqualToString:@"response"])
        return;
    
    //There is nothing to do if we encounter the response element here.
    //If we encounter the car element howevere, we want to add the carBean object to the array
    // and release the object.
    if([elementName isEqualToString:@"car"]) {
        [appDelegate.cars addObject:aCar];
        
        [aCar release];
        aCar = nil;
    }
    else
        [aCar.dataDictionary setValue:currentElementValue forKey:elementName];
    
    [currentElementValue release];
    currentElementValue = nil;
}

- (void) dealloc {
    
    [aCar release];
    [currentElementValue release];
    [super dealloc];
}

@end
